import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, Button, message, Tooltip } from 'antd';
import { DeleteOutlined, InfoCircleOutlined } from '@ant-design/icons';
import {
  DndContext,
  DragEndEvent,
  DragOverEvent,
  DragStartEvent,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  useDroppable,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import {
  useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { sopService, SOP_CUSTOMER_PROFILES } from '../services/sopService';
import { SopNode, SopChain } from '../types/sop';

const { TextArea } = Input;

interface SopStrategyModalProps {
  visible: boolean;
  onCancel: () => void;
  activeGroup: string;
  onSuccess: () => void;
  availableNodes: Record<string, string[]>;
  editingStrategy?: SopChain | null;
}

interface SortableWorkflowNodeProps {
  id: string;
  text: string;
  onDelete: (id: string) => void;
  index: number;
}

interface DraggableNodeProps {
  id: string;
  text: string;
  isNodeDraggable: (nodeName: string) => boolean;
  findNodeStage: (nodeName: string) => string;
}

// 修改DraggableNode组件，添加禁用状态
const DraggableNode: React.FC<DraggableNodeProps> = ({ 
  id, 
  text,
  isNodeDraggable,
  findNodeStage
}) => {
  const nodeText = id.replace('available-', '');
  const isDraggable = isNodeDraggable(nodeText);
  const stage = findNodeStage(nodeText);
  
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    isDragging,
  } = useSortable({ 
    id,
    disabled: !isDraggable 
  });

  const style = {
    transform: CSS.Transform.toString(transform),
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`${
        isDraggable 
          ? 'bg-gray-100 hover:bg-gray-200 cursor-grab active:cursor-grabbing' 
          : 'bg-gray-200 cursor-not-allowed opacity-50'
      } text-gray-700 p-2 rounded-md text-sm transition-colors mb-2`}
      title={!isDraggable ? `${stage}阶段已有节点` : undefined}
      {...(isDraggable ? { ...attributes, ...listeners } : {})}
    >
      {text}
    </div>
  );
};

const SortableWorkflowNode: React.FC<SortableWorkflowNodeProps> = ({ 
  id, 
  text, 
  onDelete, 
  index 
}) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div className="relative">
      {/* 步骤序号 */}
      <div className="absolute left-0 top-2 w-8 h-8 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-bold z-10">
        {index + 1}
      </div>
      
      {/* 连接线 */}
      {index > 0 && (
        <div className="absolute left-4 top-0 w-0.5 h-2 bg-gray-300"></div>
      )}
      
      <div
        ref={setNodeRef}
        style={style}
        className="ml-12 mb-4 bg-white border border-gray-200 rounded-lg p-3 shadow-sm hover:shadow-md transition-shadow cursor-grab active:cursor-grabbing"
        {...attributes}
        {...listeners}
      >
        <div className="flex items-center justify-between">
          <span className="flex-grow text-sm text-gray-700">{text}</span>
          <Button
            type="text"
            size="small"
            icon={<DeleteOutlined />}
            onClick={(e) => {
              e.stopPropagation();
              onDelete(id);
            }}
            className="text-gray-400 hover:text-red-500 flex-shrink-0 ml-2"
          />
        </div>
      </div>
      
      {/* 底部连接线 */}
      <div className="absolute left-4 top-10 w-0.5 h-8 bg-gray-300"></div>
    </div>
  );
};

interface DroppableWorkflowContainerProps {
  children: React.ReactNode;
}

const DroppableWorkflowContainer: React.FC<DroppableWorkflowContainerProps> = ({ children }) => {
  const { isOver, setNodeRef } = useDroppable({
    id: 'workflow-container',
  });

  return (
    <div
      ref={setNodeRef}
      className={`min-h-[100px] relative transition-colors ${
        isOver ? 'bg-blue-50 border-blue-200 border-dashed border-2' : ''
      }`}
    >
      {children}
    </div>
  );
};

const SopStrategyModal: React.FC<SopStrategyModalProps> = ({
  visible,
  onCancel,
  activeGroup,
  onSuccess,
  availableNodes,
  editingStrategy = null,
}) => {
  const [form] = Form.useForm();
  const [workflow, setWorkflow] = useState<string[]>([]);
  const [activeDragId, setActiveDragId] = useState<string | null>(null);
  const [overId, setOverId] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  // 根据节点名称查找所属阶段
  const findNodeStage = (nodeName: string): string => {
    for (const [stage, nodes] of Object.entries(availableNodes)) {
      if (nodes.includes(nodeName)) {
        return stage;
      }
    }
    return '未知阶段';
  };

  // 获取当前工作流中已使用的阶段
  const getUsedStages = (): Set<string> => {
    const usedStages = new Set<string>();
    workflow.forEach(nodeName => {
      const stage = findNodeStage(nodeName);
      if (stage !== '未知阶段') {
        usedStages.add(stage);
      }
    });
    return usedStages;
  };

  // 检查节点是否可拖拽（如果该阶段已有节点则不可拖拽）
  const isNodeDraggable = (nodeName: string): boolean => {
    const nodeStage = findNodeStage(nodeName);
    if (nodeStage === '未知阶段') return true;
    
    const usedStages = getUsedStages();
    return !usedStages.has(nodeStage);
  };

  // 编辑模式初始化
  useEffect(() => {
    if (visible) {
      if (editingStrategy) {
        // 编辑模式：填充表单数据
        form.setFieldsValue({
          group: editingStrategy.customer_profile,
          name: editingStrategy.name,
          scenario: editingStrategy.scenario,
          reason: editingStrategy.description,
        });
        // 填充工作流节点（按order排序）
        const sortedNodes = [...editingStrategy.nodes].sort((a, b) => a.order - b.order);
        setWorkflow(sortedNodes.map(node => node.node));
      } else {
        // 新建模式：设置默认客群
        form.setFieldsValue({
          group: activeGroup,
        });
        setWorkflow([]);
      }
    } else {
      // 模态框关闭时重置
      form.resetFields();
      setWorkflow([]);
    }
  }, [visible, editingStrategy, activeGroup, form]);

  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8,
      },
    }),
    useSensor(KeyboardSensor)
  );

  const handleDragStart = (event: DragStartEvent) => {
    const activeId = event.active.id as string;
    // 如果是从可用节点库拖拽，检查是否允许拖拽
    if (activeId.startsWith('available-')) {
      const nodeName = activeId.replace('available-', '');
      if (!isNodeDraggable(nodeName)) {
        message.warning('每个阶段只能选择一个节点');
        return;
      }
    }
    setActiveDragId(activeId);
  };

  const handleDragOver = (event: DragOverEvent) => {
    setOverId(event.over?.id as string);
  };

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    
    setActiveDragId(null);
    setOverId(null);

    if (!over) return;

    const activeId = active.id as string;
    const overId = over.id as string;

    // 从可用节点拖拽到工作流区域
    if (activeId.startsWith('available-') && overId.startsWith('workflow-')) {
      const nodeText = activeId.replace('available-', '');
      // 再次检查是否允许添加该节点
      if (!isNodeDraggable(nodeText)) {
        message.warning('每个阶段只能选择一个节点');
        return;
      }
      const overIndex = workflow.findIndex(item => `workflow-${item}` === overId);
      
      const newWorkflow = [...workflow];
      newWorkflow.splice(overIndex + 1, 0, nodeText);
      setWorkflow(newWorkflow);
    }
    // 从可用节点拖拽到容器
    else if (activeId.startsWith('available-') && overId === 'workflow-container') {
      const nodeText = activeId.replace('available-', '');
      // 再次检查是否允许添加该节点
      if (!isNodeDraggable(nodeText)) {
        message.warning('每个阶段只能选择一个节点');
        return;
      }
      setWorkflow([...workflow, nodeText]);
    }
    // 工作流内部排序
    else if (activeId.startsWith('workflow-') && overId.startsWith('workflow-')) {
      const activeIndex = workflow.findIndex(item => `workflow-${item}` === activeId);
      const overIndex = workflow.findIndex(item => `workflow-${item}` === overId);
      
      if (activeIndex !== overIndex) {
        setWorkflow(arrayMove(workflow, activeIndex, overIndex));
      }
    }
  };

  const handleDeleteWorkflowNode = (nodeId: string) => {
    const nodeText = nodeId.replace('workflow-', '');
    setWorkflow(workflow.filter(item => item !== nodeText));
  };

  const handleSave = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      if (workflow.length === 0) {
        message.warning('请至少添加一个SOP节点');
        return;
      }

      // 构建SOP节点数组
      const sopNodes: SopNode[] = workflow.map((nodeText, index) => ({
        order: index + 1,
        node: nodeText,
        stage: findNodeStage(nodeText)
      }));

      // 调用API创建或更新策略
      let result;
      if (editingStrategy) {
        // 更新策略
        result = await sopService.updateSopChain(editingStrategy.chain_id, {
          name: values.name,
          description: values.reason,
          customer_profile: values.group,
          scenario: values.scenario,
          nodes: sopNodes
        });
      } else {
        // 创建策略
        result = await sopService.createSopChain({
          name: values.name,
          description: values.reason,
          customer_profile: values.group,
          scenario: values.scenario,
          nodes: sopNodes
        });
      }

      if (result.success) {
        message.success(`${editingStrategy ? '更新' : '创建'}SOP策略成功`);
        onSuccess();
      } else {
        message.error(result.error || `${editingStrategy ? '更新' : '创建'}策略失败`);
      }
    } catch (error) {
      console.error(`${editingStrategy ? '更新' : '保存'}SOP策略失败:`, error);
      message.error(`${editingStrategy ? '更新' : '保存'}策略失败，请重试`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={editingStrategy ? "编辑SOP策略" : "新建SOP策略"}
      open={visible}
      onCancel={onCancel}
      width={1200}
      style={{ top: 20 }}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button 
          key="submit" 
          type="primary" 
          onClick={handleSave}
          loading={loading}
        >
          保存策略
        </Button>,
      ]}
    >
      <Form form={form} layout="vertical">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {/* 左侧：基本信息 */}
          <div className="md:col-span-1">
            <Form.Item
              name="group"
              label="所属客群"
              rules={[{ required: true, message: '请选择所属客群' }]}
            >
              <Select>
                {SOP_CUSTOMER_PROFILES.map(profile => (
                  <Select.Option key={profile} value={profile}>
                    {profile}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="name"
              label="策略名称"
              rules={[{ required: true, message: '请输入策略名称' }]}
            >
              <Input placeholder="例如：快速认知引导策略" />
            </Form.Item>

            <Form.Item
              name="scenario"
              label="营销场景"
              rules={[{ required: true, message: '请输入营销场景' }]}
            >
              <Input placeholder="例如：产品咨询" />
            </Form.Item>

            <Form.Item
              name="reason"
              label="策略描述"
              rules={[{ required: true, message: '请输入策略描述' }]}
            >
              <TextArea
                rows={4}
                placeholder="简述该策略的设计目的和价值"
              />
            </Form.Item>
          </div>

          {/* 右侧：SOP链路编排 */}
          <div className="md:col-span-2">
            <div className="flex items-center gap-2 mb-3">
              <h4 className="text-md font-semibold text-gray-700">SOP链路编排</h4>
              <Tooltip title="每个阶段最多只能选择一个节点">
                <InfoCircleOutlined className="text-gray-400 cursor-help" />
              </Tooltip>
            </div>
            <DndContext
              sensors={sensors}
              collisionDetection={closestCenter}
              onDragStart={handleDragStart}
              onDragOver={handleDragOver}
              onDragEnd={handleDragEnd}
            >
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* 可用节点库 */}
                <div className="bg-gray-50 p-4 rounded-lg h-96 overflow-y-auto">
                  <h4 className="text-md font-semibold text-gray-700 mb-3">可用节点库</h4>
                  <div className="space-y-4">
                    {Object.entries(availableNodes).map(([stage, nodes]) => (
                      <div key={stage}>
                        <h5 className="font-semibold text-blue-600 text-sm mb-2">{stage}</h5>
                        <SortableContext
                          items={nodes.map(node => `available-${node}`)}
                          strategy={verticalListSortingStrategy}
                        >
                          <div className="space-y-2">
                            {nodes.map(nodeText => (
                              <DraggableNode
                                key={`available-${nodeText}`}
                                id={`available-${nodeText}`}
                                text={nodeText}
                                isNodeDraggable={isNodeDraggable}
                                findNodeStage={findNodeStage}
                              />
                            ))}
                          </div>
                        </SortableContext>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 当前工作流 */}
                <div className="bg-gray-50 p-4 rounded-lg h-96 overflow-y-auto">
                  <h4 className="text-md font-semibold text-gray-700 mb-3">当前SOP链路</h4>
                  <SortableContext
                    items={workflow.map(item => `workflow-${item}`)}
                    strategy={verticalListSortingStrategy}
                  >
                    <DroppableWorkflowContainer>
                      {workflow.length === 0 ? (
                        <div className="text-gray-400 text-center py-8">
                          拖拽左侧节点到此处构建SOP链路
                        </div>
                      ) : (
                        <>
                          {workflow.map((nodeText, index) => {
                            // 插入指示线
                            const isInsert =
                              activeDragId &&
                              overId === `workflow-${nodeText}` &&
                              activeDragId.startsWith('available-');
                            return (
                              <React.Fragment key={`workflow-${nodeText}-${index}`}>
                                {isInsert && (
                                  <div className="h-4 w-full bg-blue-200 rounded my-1 animate-pulse" />
                                )}
                                <SortableWorkflowNode
                                  id={`workflow-${nodeText}`}
                                  text={nodeText}
                                  index={index}
                                  onDelete={handleDeleteWorkflowNode}
                                />
                              </React.Fragment>
                            );
                          })}
                          {/* 末尾插入线 */}
                          {activeDragId &&
                            overId === 'workflow-container' &&
                            activeDragId.startsWith('available-') && (
                              <div className="h-4 w-full bg-blue-200 rounded my-1 animate-pulse" />
                            )}
                        </>
                      )}
                    </DroppableWorkflowContainer>
                  </SortableContext>
                </div>
              </div>
            </DndContext>
          </div>
        </div>
      </Form>
    </Modal>
  );
};

export default SopStrategyModal; 